<?php
/**
 * Created by PhpStorm.
 * User: sunfan
 * Date: 2017/2/4
 * Time: 9:55
 */

namespace Api\Controller;
use Think\Controller;


class MapiBaseController extends Controller {
    //返回
    protected $data;

    protected function _initialize(){
        header("Access-Control-Allow-Origin: *");
        $data = $_REQUEST;
        $this->writeLog("收到用户:".json_encode($data));
        if(is_null($data)){
            $this->ApiReturn(10001,'数据格式错误');
        }
        $this->data=$data;

        //自动加入配置
        $mall_config_list = M('mall_config')->select();
        foreach ($mall_config_list as $key => $mall_config) {
            $setting[$mall_config['code']] = $mall_config['value'];
        }
        $setting['SITE_URL'] = 'http://'.$_SERVER['HTTP_HOST'].'/';
        C($setting);

    }
    //api返回
    protected function ApiReturn($code,$msg,$data=array()) {
        $arr['code']=$code;
        $arr['msg'] = $msg;
        $arr['data'] = $data;
        $arr['time']=time();
        $a = $this->data;
        echo str_replace('\/',"/",json_encode($arr));
        $this->writeLog("发出:".json_encode($arr));
        die();
    }


    function inputFilter($content)
    {
        if(is_string($content) ) {
            return $this->clean($content);
        }
        elseif(is_array($content)){
            foreach ( $content as $key => $val ) {
                $content[$key] = inputFilter($val);
            }
            return $content;
        }
        elseif(is_object($content)) {
            $vars = get_object_vars($content);
            foreach($vars as $key=>$val) {
                $content->$key = inputFilter($val);
            }
            return $content;
        }
        else{
            return $content;
        }
    }
    function clean($v) {
        //判断magic_quotes_gpc是否为打开
        if (!get_magic_quotes_gpc()) {
            //进行magic_quotes_gpc没有打开的情况对提交数据的过滤
            $v = addslashes($v);
        }
        $v=str_replace("update", "", $v);
        //把'_'过滤掉
        $v = str_replace("_", "\_", $v);
        //把'%'过滤掉
        $v = str_replace("%", "\%", $v);
        //把'*'过滤掉
        $v = str_replace("*", "\*", $v);
        //回车转换
        $v = nl2br($v);
        //html标记转换
        $v = htmlspecialchars($v);
        return $v;
    }

    function writeLog($mes)
    {
        $years = date('Y-m-d');
        //设置路径目录信息
        $url  = '../temp/logs/'.$years.'/'.$years.'_request_log.txt';
        //取出目录路径中目录(不包括后面的文件)
        $dir_name = dirname($url);
        //如果目录不存在就创建
        if(!file_exists($dir_name)) {
            $res = mkdir(iconv("UTF-8","GBK",$dir_name),0777,true);
        }
        file_put_contents($url,date('Y-m-d H:i:s').":".$mes."\n",FILE_APPEND);
    }
    function createNoncestr( $length = 32 )
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str ="";
        for ( $i = 0; $i < $length; $i++ )  {
            $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return $str;
    }
    /**
     * 检查手机号码格式
     * @param $mobile 手机号码
     * @return bool;
     */
    protected function check_mobile($mobile){
        if(preg_match('/1[0123456789]\d{9}$/',$mobile))
            return true;
        return false;
    }

    /**
     * 检查邮箱地址格式
     * @param $email 邮箱地址
     * @return bool;
     */
    protected function check_email($email){
        if(filter_var($email,FILTER_VALIDATE_EMAIL))
            return true;
        return false;
    }
    /**
     * @param string $name  字段名
     * @param string $val   字段值
     * @param string $msg   返回的错误信息
     * @param int $type     验证类型 : 1 是否为空 ，2 范围 , 3 手机号 ,4 邮箱
     * @param array $rage   type 为 2 的时候传 最小和最大值
     * @return bool
     * 欢迎扩展
     */
    public function validate($name='id',$val='',$msg='',$type=1, $rage=array(0,100)){

        if($type == 1){
            if(!$val){
                $this->ApiReturn(-1, false,$msg?$msg:'缺少必传参数'.$name);
            }
        }else{
            if(!$val && $val!=0){
                $this->ApiReturn(-1, false,$msg?$msg:'缺少必传参数 '.$name);
            }
            switch ($type){
                case 2:    // 范围
                    if($val < $rage[0] || $val > $rage[1] ){
                        $this->ApiReturn(-1,false, $msg?$msg:'参数值不在范围之内');
                    }
                    break;
                case 3:  // 手机号
                    if(!$this->check_mobile($val)){
                        $this->ApiReturn(-1, false,$msg?$msg:'手机号码不正确');
                    }
                    break;
                case 4:  // email
                    if(!$this->check_email($val)){
                        $this->ApiReturn(-1,false, $msg?$msg:'邮箱地址不正确');
                    }
                    break;
                case 5:
                    if(!is_numeric($val) || $val < $rage[0]){
                        $this->ApiReturn(-1,false, $msg?$msg:'参数'.$name.'格式错误');
                    }
                    break;
                default:
                    $this->ApiReturn(-1, false,'未检测到验证类型');
                    break;
            }
        }
        return true;
    }
}